package com.bestv.bsr.core.service.impl.ah;

import cn.hutool.core.collection.CollectionUtil;
import com.bestv.bsr.core.constants.ServiceCodeEnum;
import com.bestv.bsr.core.context.RecommendContext;
import com.bestv.bsr.core.entities.vo.RecDataVo;
import com.bestv.bsr.core.entities.vo.RecGroupListVo;
import com.bestv.bsr.core.entities.vo.RecItemVoListVo;
import com.bestv.bsr.core.exceptions.ServiceException;
import com.bestv.bsr.core.properties.AHRecommendProperties;
import com.bestv.bsr.core.properties.GlobalProperties;
import com.bestv.bsr.core.service.AbstractRecommendEngine;
import com.bestv.bsr.core.service.impl.ah.dto.AHRequestParam;
import com.bestv.bsr.core.service.impl.ah.dto.AHResponseDto;
import com.bestv.bsr.core.service.impl.ah.dto.AHZYWLResponseDto;
import com.bestv.bsr.core.service.impl.ah.remote.AHRemoteService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author taojiacheng
 */
public abstract class AbstractAHRecommendEngine extends AbstractRecommendEngine {

    public static final String APP_ID = "00001";
    @Autowired
    protected AHRecommendProperties properties;
    @Autowired
    protected AHRemoteService ahRemoteService;
    @Autowired
    protected GlobalProperties globalProperties;

    @Override
    public void init(RecommendContext recommendContext) {
        // 场景参数转换
        String sceneId = recommendContext.getSceneId();
        Map<String, String> sceneConvertMap = properties.getSceneConvertMap();
        String channel = sceneConvertMap.get(sceneId);
        if (StringUtils.isBlank(channel)) {
            throw new ServiceException(ServiceCodeEnum.SCENE_ID_NOT_SUPPORTED);
        }
        if (channel.contains(":")) {
            channel = channel.substring(0, channel.indexOf(":"));
        }
        recommendContext.setChannel(channel);
    }

    /**
     * 构建接口请求参数
     */
    protected AHRequestParam buildRequestParam(RecommendContext recommendContext, boolean isSetVideoId) {
        AHRequestParam requestParam = new AHRequestParam();
        requestParam.setId(APP_ID + RandomStringUtils.randomAlphanumeric(16));
        requestParam.setUserid(recommendContext.getUserAccount());
        requestParam.setChannel(recommendContext.getChannel());
        requestParam.setCatename(recommendContext.getCateName());
        requestParam.setMac(recommendContext.getMac());
        if (isSetVideoId) {
            if (CollectionUtils.isEmpty(recommendContext.getItemCodes())) {
                throw new ServiceException(ServiceCodeEnum.ITEM_CODES_IS_EMPTY);
            }
            requestParam.setVideoid(recommendContext.getItemCodes().get(0));
        }
        return requestParam;
    }


    protected AHResponseDto handlerZYWLResp(AHZYWLResponseDto responseDto) {
        AHZYWLResponseDto.ZYWLRespData data = responseDto.getData();
        List<AHZYWLResponseDto.ZYWLRespCates> cateS = data.getCates();
        List<RecGroupListVo> groupListVos = cateS.stream().map(cate -> {
            List<AHZYWLResponseDto.ZYWLRespItems> items = cate.getItems();
            List<RecItemVoListVo> recThirdInfoVos = items.stream().map(item -> {
                String apkUrl = item.getApkurl();
                String cls = item.getCls();
                String pkg = item.getPkg();
                String backType = item.getBacktype();
                RecItemVoListVo itemVoListVo = new RecItemVoListVo(apkUrl, cls, pkg, backType);
                itemVoListVo.setItemCode(item.getItemid());
                itemVoListVo.setItemName(item.getItemname());
                itemVoListVo.setCpid(item.getCpid());
                itemVoListVo.setMarkPos(item.getCornerposition());
                itemVoListVo.setMarkUrl(item.getCornerurl());
                itemVoListVo.setPoster(item.getPicurl());
                itemVoListVo.setMedMarkPos("");
                itemVoListVo.setMedMarkUrl("");
                itemVoListVo.setVersioncode(item.getParam1());
                return itemVoListVo;
            }).collect(Collectors.toList());
            RecGroupListVo recGroupListVo = new RecGroupListVo();
            recGroupListVo.setItemType(cate.getCatename());
            recGroupListVo.setRecItemVoList(recThirdInfoVos);
            return recGroupListVo;
        }).collect(Collectors.toList());
        String displayTracker = "";
        if (CollectionUtil.isNotEmpty(cateS)) {
            displayTracker = cateS.get(0).getDisplay_tracker();
        }
        return AHResponseDto.builder()
                .recResultId(data.getTrace_id())
                .displayTracker(displayTracker)
                .groupList(groupListVos)
                .build();
    }


    /**
     * 结果转换
     */
    protected RecDataVo convertResult(AHResponseDto ahResponseDto, RecommendContext recommendContext) {
        List<RecGroupListVo> recItemGroupVoList = new ArrayList<>();
        List<RecItemVoListVo> recItemVoListVos = new ArrayList<>();
        for (RecGroupListVo recGroupListVo : ahResponseDto.getGroupList()) {
            List<RecItemVoListVo> recThirdInfoVos = recGroupListVo.getRecItemVoList();
            boolean versionFlag = comparePackNum(recommendContext.getTvProfile());
            for (RecItemVoListVo itemVoListVo : recThirdInfoVos) {
                boolean isNotEmptyFlag = StringUtils.isNotEmpty(itemVoListVo.getApkurl())
                        && StringUtils.isNotEmpty(itemVoListVo.getPkg())
                        && StringUtils.isNotEmpty(itemVoListVo.getCls());
                if (StringUtils.equals(properties.getCpid(), itemVoListVo.getCpid())) {
                    recItemVoListVos.add(itemVoListVo);
                } else if (versionFlag && isNotEmptyFlag) {
                    recItemVoListVos.add(itemVoListVo);
                }
            }
        }
        // 根据size值返回推荐节目的数量 todo size 处理
        if (recommendContext.getSize() < recItemVoListVos.size()) {
            recItemVoListVos = recItemVoListVos.subList(0, recommendContext.getSize());
        }
        RecGroupListVo recItemGroupVo = new RecGroupListVo();
        recItemGroupVo.setItemType(recommendContext.getItemTypes().get(0));
        recItemGroupVo.setRecItemVoList(recItemVoListVos);
        recItemGroupVoList.add(recItemGroupVo);
        RecDataVo resultVo = new RecDataVo();
        resultVo.setAppId(APP_ID);
        resultVo.setRecResultId(ahResponseDto.getRecResultId());
        resultVo.setDisplayTracker(ahResponseDto.getDisplayTracker());
        resultVo.setGroupList(recItemGroupVoList);
        return resultVo;
    }

    /**
     * 获得当前版本是否大于等于配置版本
     */
    private Boolean comparePackNum(String profile) {
        if (StringUtils.isBlank(profile)) {
            return false;
        }
        String[] num1Sub = profile.split("_")[3].split("\\.");
        String[] num2Sub = properties.getApkVersion().split("_")[3].split("\\.");
        int num = Math.min(num1Sub.length, num2Sub.length);
        for (int i = 0; i < num; i++) {
            int result;
            try {
                result = Integer.parseInt(num1Sub[i]) - Integer.parseInt(num2Sub[i]);
            } catch (NumberFormatException e) {
                return false;
            }
            if (result > 0) {
                return true;
            } else if (result < 0) {
                return false;
            }
        }
        return true;
    }


}
